package com.rongshu.view.home.fragment;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.rongshu.R;
import com.rongshu.utils.Constant;
import com.rongshu.utils.ControlScrollLayoutManager;
import com.rongshu.view.base.AdapterListener;
import com.rongshu.view.base.BaseFragment;
import com.rongshu.view.discovery.activity.SearchActivity;
import com.rongshu.view.discovery.activity.UserHomePageActivity;
import com.rongshu.view.discovery.adapter.RecommendAuthorAdapter;
import com.rongshu.view.discovery.adapter.RecommendEditorAdapter;
import com.rongshu.view.discovery.bean.ArticleDetaisRequest;
import com.rongshu.view.home.activity.SingleArticleDetailsActivity;
import com.rongshu.view.home.adapter.RecommendArticleAdapter;
import com.rongshu.view.home.bean.BannerResponse;
import com.rongshu.view.home.bean.RecommendAuthorResponse;
import com.rongshu.view.home.bean.RecommendEditResponse;
import com.rongshu.view.home.bean.RecommendReaderResponse;
import com.rongshu.view.home.contract.DiscoveryView;
import com.rongshu.view.home.presenter.DiscoveryPresenter;
import com.rongshu.view.web.ActivityWeb;
import com.rongshu.widget.RoundImageView;
import com.rongshu.widget.banner.Banner;
import com.rongshu.widget.banner.listener.OnBannerListener;
import com.rongshu.widget.banner.loader.BannerImgLoderCallBack;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utils.DensityUtil;
import com.utils.FastClickUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * created by zhengeweis on 2018/10/30.
 * description：发现页面
 */
public class DiscoveryFragment extends BaseFragment<DiscoveryPresenter> implements DiscoveryView,
        OnBannerListener, BannerImgLoderCallBack<RoundImageView> {
    @BindView(R.id.banner_view)
    Banner bannerView;
    @BindView(R.id.article_list)
    RecyclerView articleList;
    @BindView(R.id.recommend_editor_list)
    RecyclerView editorList;
    @BindView(R.id.recommend_author_list)
    RecyclerView authorList;
    @BindView(R.id.refresh_view)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.head_content)
    RelativeLayout headContent;
//    @BindView(R.id.event_a)
//    ImageView eventA;
//    @BindView(R.id.event_b)
//    ImageView eventB;

    private List<BannerResponse.ResponseBean> bannerList;
    private List<RecommendAuthorResponse.ResponseBean> authorResponseList;
    private List<RecommendEditResponse.ResponseBean> editors;
    private List<RecommendReaderResponse.ResponseBean> readers;
    private RecommendArticleAdapter readerLikeArticleAdapter;
    private RecommendAuthorAdapter authorAdapter;
    private RecommendEditorAdapter editorAdapter;
    private int authorPageIndex = 1;
    private int authorPageSize = 5;
    private int authorTotal = 1;//推荐读者总页数
    private int readerPageIndex = 1;
    private int readerPageSize = 10;
    private RecommendReaderResponse.ResponseBean bean;
    private GridLayoutManager editorManager;
    private int serialPosition = -1;
//    private EventListResponse events;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragemnt_discovery;
    }

    @Override
    protected void initViews() {
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) headContent.getLayoutParams();
        layoutParams.topMargin = DensityUtil.getStateBar(getActivity());
        headContent.setLayoutParams(layoutParams);
        refreshLayout.setEnableLoadmore(true);
        //banner
        bannerList = new ArrayList<>();
        bannerView.setImages(bannerList).setImageLoader(this).setOnBannerListener(this);

        //热门作者列表
        GridLayoutManager authorManager = new GridLayoutManager(getActivity(), 5);
        authorResponseList = new ArrayList<>();
        authorList.setLayoutManager(authorManager);
        authorAdapter = new RecommendAuthorAdapter(getActivity(), authorResponseList);
        authorList.setAdapter(authorAdapter);
        authorAdapter.setAdapterListener(new AdapterListener() {
            @Override
            public void callBack(Object object) {
                if (object instanceof RecommendAuthorResponse.ResponseBean) {
                    RecommendAuthorResponse.ResponseBean bean = (RecommendAuthorResponse.ResponseBean) object;
                    Intent intent = new Intent(getActivity(), UserHomePageActivity.class);
                    int userid = bean.getUserid();
                    intent.putExtra(Constant.USER_ID, userid);
                    startActivity(intent);
                }
            }
        });

        //栏目精选
        editorManager = new GridLayoutManager(getActivity(), 3);
        editorList.setLayoutManager(editorManager);
        editors = new ArrayList<>();
        editorAdapter = new RecommendEditorAdapter(getActivity(), editors);
        editorList.setAdapter(editorAdapter);

        //读者赞赏
        ControlScrollLayoutManager layoutManager = new ControlScrollLayoutManager(getActivity());
        layoutManager.setScrollEnabled(false);
        articleList.setLayoutManager(layoutManager);
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.recommend_article_divider));
        articleList.addItemDecoration(divider);
        //删除动画
        DefaultItemAnimator defaultItemAnimator = new DefaultItemAnimator();
        defaultItemAnimator.setRemoveDuration(100);
        articleList.setItemAnimator(defaultItemAnimator);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        readers = new ArrayList<>();
        readerLikeArticleAdapter = new RecommendArticleAdapter(getActivity(), readers);
        articleList.setAdapter(readerLikeArticleAdapter);
        readerLikeArticleAdapter.setAdapterListener(new AdapterListener() {
            @Override
            public void callBack(Object object) {
                bean = (RecommendReaderResponse.ResponseBean) object;
                presenter.deleteRead(bean.getContribute_id());
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                readerPageIndex = 1;
                authorPageIndex = 1;
                refreshLayout.resetNoMoreData();
                presenter.getRecommedReader(readerPageIndex, readerPageSize);
                presenter.getRecommendAuthor(authorPageIndex, authorPageSize);
                if (bannerList.size() == 0) {
                    presenter.getBannerImg();
                }
                if (editors.size() == 0){
                    presenter.getRecommendEdit();
                }
//                presenter.getEvents();
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                readerPageIndex++;
                presenter.getRecommedReader(readerPageIndex, readerPageSize);
            }
        });
    }

    @Override
    protected void initData() {
        setPresenter(new DiscoveryPresenter(getActivity()), this);
        presenter.getRecommedReader(readerPageIndex, readerPageSize);
        presenter.getBannerImg();
//        presenter.getEvents();
        presenter.getRecommendAuthor(authorPageIndex, authorPageSize);
        presenter.getRecommendEdit();
    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        bannerView.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //开始轮播
        bannerView.stopAutoPlay();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        bannerView.releaseBanner();
    }

    @OnClick({R.id.head_content, R.id.update_recommend_author})
    public void onViewClicked(View view) {
        if (FastClickUtils.isFastClick()) {
            return;
        }
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.update_recommend_author:
                if (authorPageIndex < authorTotal) {
                    authorPageIndex++;
                } else {
                    authorPageIndex = 1;
                }
                presenter.getRecommendAuthor(authorPageIndex, authorPageSize);
                break;
            case R.id.head_content:
                intent.setClass(getActivity(), SearchActivity.class);
                startActivity(intent);
                break;
//            case R.id.more_event:
//                intent.setClass(getActivity(), MoreEventActivity.class);
//                startActivity(intent);
//                break;
//            case R.id.event_a:
//                EventListResponse.ResponseBean beanA = events.getResponse().get(0);
//                if (beanA != null) {
//                    intent.setClass(getActivity(), ActivityWeb.class);
//                    intent.putExtra(Constant.INTENT_TITLE, beanA.getTitle());
//                    intent.putExtra(Constant.INTENT_H5, beanA.getUrlAddress());
//                    startActivity(intent);
//                }
//                break;
//            case R.id.event_b:
//                EventListResponse.ResponseBean beanB = events.getResponse().get(0);
//                if (beanB != null) {
//                    intent.setClass(getActivity(), ActivityWeb.class);
//                    intent.putExtra(Constant.INTENT_TITLE, beanB.getTitle());
//                    intent.putExtra(Constant.INTENT_H5, beanB.getUrlAddress());
//                    startActivity(intent);
//                }
//                break;
        }
    }

    @Override
    public void bannerResponse(BannerResponse bannerResponse) {
        if (bannerResponse != null && bannerResponse.getResponse() != null) {
            bannerList.clear();
            bannerList.addAll(bannerResponse.getResponse());
            bannerView.update(bannerList);
        }
    }

    @Override
    public void recommendAuthorResponse(RecommendAuthorResponse authorResponse) {
        refreshLayout.setEnableAutoLoadmore(true);
        int total = authorResponse.getTotal();//总条目
        int i = total % authorPageSize;
        if (i > 0) {
            authorTotal = total / authorPageSize + 1;
        } else {
            authorTotal = total / authorPageSize;
        }
        if (authorPageIndex != 1 &&
                (authorResponse.getResponse() == null || authorResponse.getResponse().size() == 0)) {
            //如果请求该页面没有内容，则重置页数，再请求一下第一页的数据
            authorPageIndex = 1;
            presenter.getRecommendAuthor(authorPageIndex, authorPageSize);
        } else {
            authorResponseList.clear();
            authorResponseList.addAll(authorResponse.getResponse());
            authorAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void recommendEditResponse(RecommendEditResponse authorResponse) {
        editors.clear();
        editors.addAll(authorResponse.getResponse());
        for (int i = 0; i < editors.size(); i++) {
            if (TextUtils.equals(editors.get(i).getTitle(), "连载")) {
                serialPosition = i;
            }
        }
        if (serialPosition != -1) {
            editorManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    return position == serialPosition ? 2 : 1;
                }
            });
        }
        editorAdapter.notifyDataSetChanged();
    }

    @Override
    public void recommendReaderResponse(RecommendReaderResponse readerResponse) {
        if (readerPageIndex == 1) {
            readers.clear();
        }
//        refreshLayout.setEnableLoadmore(true);
        if (refreshLayout.isLoading()) {
            refreshLayout.finishLoadmore();
        }
        if (refreshLayout.isRefreshing()) {
            refreshLayout.finishRefresh();
        }
        readers.addAll(readerResponse.getResponse());
        readerLikeArticleAdapter.notifyDataSetChanged();
        if (readerResponse.getResponse().size() == 0) {
            refreshLayout.setLoadmoreFinished(true);
        }
    }

    /**
     * 加载banner图片
     */
    @Override
    public void displayImage(Context context, Object obj, RoundImageView imageView) {
        if (obj instanceof BannerResponse.ResponseBean) {
            BannerResponse.ResponseBean bean = (BannerResponse.ResponseBean) obj;
            Glide.with(getActivity()).load(bean.getImgUrl()).into(imageView);
        }
    }

    /**
     * banner item点击监听
     */
    @Override
    public void OnBannerItemClick(int position) {
        if (position < bannerList.size()) {
            BannerResponse.ResponseBean bannerItemBean = bannerList.get(position);
            if (bannerItemBean != null) {
                Intent intent = new Intent();
                //urlType (1.文章，2.连载，3.外部)
                switch (bannerItemBean.getUrlType()) {
                    case 1:
                        if (!TextUtils.isEmpty(bannerItemBean.getUrlAddress())) {
                            intent.setClass(getActivity(), SingleArticleDetailsActivity.class);
                            ArticleDetaisRequest articleDetaisRequest = new ArticleDetaisRequest();
                            articleDetaisRequest.setContribute_id(Integer.valueOf(bannerItemBean.getUrlAddress()));
                            articleDetaisRequest.setType(Constant.FROM_MAIN);
                            intent.putExtra(Constant.ARTICLE_DETAILS_REQUEST, articleDetaisRequest);
                            startActivity(intent);
                        }
                        break;
                    case 2:
                        break;
                    case 3:
                        intent.setClass(getActivity(), ActivityWeb.class);
                        intent.putExtra(Constant.INTENT_H5, bannerItemBean.getUrlAddress());
                        startActivity(intent);
                        break;
                }
            }
        }
    }

//    @Override
//    public void eventsResponse(EventListResponse response) {
//        this.events = response;
//        List<EventListResponse.ResponseBean> eventList = response.getResponse();
//        if (eventList.size() > 0) {
//            GlideUtils.loadImageView(getActivity(), eventA, eventList.get(0).getImgUrl());
//        }
//        if (eventList.size() > 1) {
//            GlideUtils.loadImageView(getActivity(), eventB, eventList.get(1).getImgUrl());
//        }
//    }
}
